package com.linksfield.topup.utils;

import com.linksfield.topup.entity.common.ServicePlanOrderRecord;
import com.linksfield.topup.entity.enumm.ExcelTitleEnum;
import com.linksfield.topup.entity.interfaces.ordermanage.orderexport.request.RequestOrderExport;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author JonyChen
 * @ClassName: ExcelUtil
 * @Description: excel 导入数据
 * @date 2018年8月13日
 * @time 上午10:28:48
 */
public class ExcelUtil {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static Logger logger = Logger.getLogger(ExcelUtil.class);
    //2003- 版本的excel

    private final static String excel2003L = ".xls";

    //2007+ 版本的excel

    private final static String excel2007U = ".xlsx";

    /**
     * 描述：获取IO流中的数据，组装成List<List<Object>>对象
     *
     * @param file
     * @return
     * @throws Exception
     */
    public List<List<Object>> importExcel(File file) throws Exception {
        List<List<Object>> list = null;

        //创建Excel工作薄
        Workbook work = this.getWorkbook(file);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }

            //遍历当前sheet中的所有行
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                if (row == null || row.getFirstCellNum() == j) {
                    continue;
                }

                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    li.add(this.getCellValue(cell));
                }
                list.add(li);
            }
        }
        return list;
    }

    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     *
     * @param file
     * @return
     * @throws Exception
     */
    public Workbook getWorkbook(File file) throws Exception {
        Workbook wb = null;
        String fileType = file.getName().substring(file.getName().lastIndexOf("."));
        if (excel2003L.equals(fileType)) {
            wb = new HSSFWorkbook(new FileInputStream(file));
        } else if (excel2007U.equals(fileType)) {
            wb = new XSSFWorkbook(new FileInputStream(file));
        } else {
            throw new Exception("解析的文件格式有误！");
        }
        return wb;
    }

    /**
     * 描述：对表格中数值进行格式化
     *
     * @param cell
     * @return
     */
    public Object getCellValue(Cell cell) {
        //用String接收所有返回的值
        String value = null;
        DecimalFormat df = new DecimalFormat("0");
        //格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
        //日期格式化
        DecimalFormat df2 = new DecimalFormat("0.00");
        //格式化数字

        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                //String类型的数据
                value = cell.getStringCellValue();
                break;

            case Cell.CELL_TYPE_NUMERIC:
                //数值类型(取值用cell.getNumericCellValue() 或cell.getDateCellValue())
                if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                    value = df.format(cell.getNumericCellValue());
                } else if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
                } else {
                    value = df2.format(cell.getNumericCellValue());
                }
                break;

            case Cell.CELL_TYPE_BOOLEAN:
                //Boolean类型
                value = String.valueOf(cell.getBooleanCellValue());
                break;


            case Cell.CELL_TYPE_FORMULA:
                //表达式类型
                value = String.valueOf(cell.getCellFormula());
                break;

            case Cell.CELL_TYPE_ERROR:
                //异常类型 不知道何时算异常
                value = String.valueOf(cell.getErrorCellValue());
                break;

            case Cell.CELL_TYPE_BLANK:
                //空，不知道何时算空
                value = "";
                break;

            default:
                value = "";
                break;
        }
        if (value.equals("") || value == null) {
            value = "";
        }
        if (cell == null) {
            return "";
        }
        return value;
    }

    /**
     * 根据resultList生成Excel,但是只是生成xlsx为后缀格式的Excel，只能Excel 2007以上的版本可以打开
     * 可生成多个工作表，每个工作表最多60000行数据，可以将缓存中的数据先存放到硬盘里再清理缓存
     *
     * @param response
     * @param fileName
     * @param nameArray
     * @param rtnList
     * @throws Exception
     */
    public static void exportExcel2007(HttpServletResponse response,
                                       String fileName, String[] nameArray, String[] keyArray,
                                       List<Map<String, Object>> rtnList) {
        int maxRow = 60000;
        try {
            OutputStream os = response.getOutputStream();
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xlsx");
            response.setContentType("application/msexcel");
            // 内存中缓存记录行数
            int rowAccess = 100;
            SXSSFWorkbook wb = new SXSSFWorkbook(rowAccess);
            int listSize = rtnList.size();
            // 总工作表
            int sheetNum = listSize / 60000 + 1;
            // 总列数
            int cellTotal = nameArray.length;
            // 数据list的取值下标
            int listNum = 0;
            for (int i = 0; i < sheetNum; i++) {
                Sheet sh = wb.createSheet("order list" + String.valueOf(i));
                // 每个SHEET有60000ROW
                for (int rowNum = 0; rowNum <= maxRow; rowNum++) {
                    Row row = sh.createRow(rowNum);
                    // 每行有cellTotal个CELL
                    if (rowNum == 0) {
                        for (int cellNum = 0; cellNum < cellTotal; cellNum++) {
                            Cell cell = row.createCell(cellNum);
                            cell.setCellValue(nameArray[cellNum]);
                        }
                    } else {
                        // 判断是否已取完数据
                        if (listNum < listSize) {
                            Map<String, Object> map = rtnList.get(listNum);
                            listNum++;
                            for (int cellNum = 0; cellNum < cellTotal; cellNum++) {
                                Cell cell = row.createCell(cellNum);
                                String key = keyArray[cellNum];
                                String value = map.get(key) != null ? map.get(key).toString() : "";
                                cell.setCellValue(value);
                            }
                        } else {
                            break;
                        }
                    }
                    // 每当行数达到设置的值就刷新数据到硬盘,以清理内存
                    if (rowNum % rowAccess == 0) {
                        ((SXSSFSheet) sh).flushRows();
                    }
                }
            }
            wb.write(os);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     *在数组最后面添加元素
     * @param arr
     * @param str
     * @return
     */
    public static String[] listConvertArr(String[] arr, String str) {
        List<String> list = new ArrayList(Arrays.asList(arr));
        list.add(str);
        return list.toArray(new String[list.size()]);
    }

    /**
     * 生成excel表头
     */
    public static String[] createTitle(String[] arr) {
        String[] title = new String[arr.length];
        if (arr != null && arr.length > 0) {
            for (int i = 0; i < arr.length; i++) {
                title[i] = ExcelTitleEnum.getNameByKey(arr[i]);
            }
        }
        return title;
    }

    /**
     * 将List<Object>转成List<Map<String,Object>>
     */
    public static <T> List<Map<String, Object>> listConvert(List<T> list) {
        List<Map<String, Object>> list_map = new ArrayList<Map<String, Object>>();
        try {
            for (T t : list) {
                Field[] fields = t.getClass().getDeclaredFields();
                Map<String, Object> m = new HashMap<String, Object>();
                for (Field field : fields) {
                    String keyName = field.getName();
                    if ("serialVersionUID".equals(keyName)) {
                        continue;
                    }
                    PropertyDescriptor pd = new PropertyDescriptor(keyName, t.getClass());
                    // 获得getter方法
                    Method getMethod = pd.getReadMethod();
                    // 执行get方法返回一个Object
                    Object o = getMethod.invoke(t);
                    m.put(keyName, o);
                }
                list_map.add(m);
            }
            return list_map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 按照默认的列表导出
     * @param orderList
     * @param request
     * @return
     */
    public Integer defaultExport(List<ServicePlanOrderRecord> orderList, RequestOrderExport request, HttpServletResponse response) {

        // Excel表头
        String[] title = {"所属企业", "支付编号", "设备识别码", "套餐名称", "订购周期", "订单总额", "货币单位", "下单时间", "订单状态", "支付状态", "订单激活时间"};
        // sheet名
        String sheetName = "Order List";
        String fileName = "ORDER_" + request.getStartDate() + "-" + request.getEndDate();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet(sheetName);
        HSSFRow row = sheet.createRow(0);
        // 这个for循环输出表头到Excel

        for (int i = 0; i < title.length; i++) {
            HSSFCell cell = row.createCell(i);
            // 新增的四句话，设置CELL格式为文本格式
            HSSFCellStyle cellStyle2 = workbook.createCellStyle();
            HSSFDataFormat format = workbook.createDataFormat();
            cellStyle2.setDataFormat(format.getFormat("@"));
            cell.setCellStyle(cellStyle2);

            cell.setCellValue(title[i]);
            cell.setCellType(Cell.CELL_TYPE_STRING);
            //  excel标题行宽度自适应
            sheet.setColumnWidth(i, title[i].getBytes().length * 256);
        }

        // 这个for循环把获取的数据写入到对应的Excel表格中
        for (int i = 0; i < orderList.size(); i++) {
            row = sheet.createRow(i + 1);
            // 这句话的意思是：row.createCell(0)第I行第0个坐标单元格应付赋值是多少，和你的titile对应上就是了，自己往下写
            row.createCell(0).setCellValue(orderList.get(i).getPartnerName());
            row.createCell(1).setCellValue(orderList.get(i).getPayId());
            row.createCell(2).setCellValue(orderList.get(i).getDeviceCode());
            row.createCell(3).setCellValue(orderList.get(i).getServicePlanShowName());

            if (orderList.get(i).getPackageType().equals("0") || orderList.get(i).getPackageType().equals("1")) {
                row.createCell(4).setCellValue(orderList.get(i).getOrderPeriod() + "天");
            } else if (orderList.get(i).getPackageType().equals("2")) {
                row.createCell(4).setCellValue(orderList.get(i).getOrderPeriod() + "个月");
            } else if (orderList.get(i).getPackageType().equals("3")) {
                row.createCell(4).setCellValue(Integer.parseInt(orderList.get(i).getOrderPeriod()) * 3 + "个月");
            } else if (orderList.get(i).getPackageType().equals("4")) {
                row.createCell(4).setCellValue(Integer.parseInt(orderList.get(i).getOrderPeriod()) * 6 + "个月");
            } else if (orderList.get(i).getPackageType().equals("5")) {
                row.createCell(4).setCellValue(orderList.get(i).getOrderPeriod() + "年");
            }
            row.createCell(5).setCellValue(orderList.get(i).getPayAmount());
            row.createCell(6).setCellValue(orderList.get(i).getPayCurrency());
            try {
                row.createCell(7).setCellValue(sdf.format(s.parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orderList.get(i).getCreateDate()))));
                if (StringUtils.isNotBlank(orderList.get(i).getOrderStartDate())) {
                    row.createCell(10).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(orderList.get(i).getOrderStartDate())));
                } else {
                    row.createCell(10).setCellValue("-");
                }
            } catch (Exception e) {
                logger.info("时间转换发生异常：" + e);
                return 404;
            }
            if (orderList.get(i).getPackageStatus().equals("1")) {
                row.createCell(8).setCellValue("未启用");
            } else if (orderList.get(i).getPackageStatus().equals("2")) {
                row.createCell(8).setCellValue("在使用");
            } else if (orderList.get(i).getPackageStatus().equals("3")) {
                row.createCell(8).setCellValue("已取消");
            } else {
                row.createCell(8).setCellValue("-");
            }
            if (orderList.get(i).getPayStatus().equals("1")) {
                row.createCell(9).setCellValue("已支付");
            } else if (orderList.get(i).getPayStatus().equals("2")) {
                row.createCell(9).setCellValue("已退款");
            } else {
                row.createCell(9).setCellValue("-");
            }

        }
        try {
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
            response.setContentType("application/msexcel");
            response.setCharacterEncoding("UTF-8");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();

            return response.getStatus();

        } catch (Exception e) {
            logger.info("导出发生异常：" + e);
            return 404;
        }

    }
}